#!/usr/bin/php -q
<?php
    /**
    * @author trungdt
    * @since jan 9, 2013
    * @copyright Absoft Viet Nam Software Solution
    * @version 1.0
    * 
    * Todo:
    * - Check timeout: more than 30 mins, need to start script again
    * - Wait for last instance finished
    * - Report error
    */
  error_reporting(E_ALL);
  
  function __realpath($path) {
        $path = str_replace('\\','/',realpath($path));
        if ($path{1} == ':') {
            // We can't just check for C:/, because windows users may have the IIS webroot on X: or F:, etc.
            $path = substr($path,2);
        }
        return $path;
    }
  
  echo "Starting ...\r\n"  ;
  define('EXPONENT', "ABSoft - Auto Video Converting for iPhone / iPad");
  define('BASE',__realpath(dirname(__FILE__)).'/../');
  define('BASE_DIR',__realpath(dirname(__FILE__)).'/');
  
  include(BASE_DIR."func.php");
  include(BASE_DIR."../conf/config.php");
  //ini_set('max_execution_time', 300);
  
  // inital the database connection
  require_once(BASE_DIR."../subsystems/database.php");
  
  $db = exponent_database_connect(DB_USER,DB_PASS,DB_HOST.':'.DB_PORT,DB_NAME);
  
  if (!$db->isValid())
  {
      echo "Connect to database not successfull... Terminating .... \r\n";
      exit(0);
  }
  echo "Database connect sucessful ...\r\n"  ;
  
  // fill data for cases and documents . One time: max 2 videos
  $data = array();
  $sql="SELECT {$db->prefix}profilemodule_cases.id master_id, {$db->prefix}profilemodule_cases.* FROM `{$db->prefix}profilemodule_cases` WHERE mp4_file = '' AND file_video <> '' AND id NOT IN (SELECT item_id FROM {$db->prefix}videoconvert_issue where item_type = 0) LIMIT 0, 1";
  
  //$temp = $db->selectObject("profilemodule_cases", "");
  $temp = $db->selectObjectsBySql($sql);
  if (count($temp) > 0 &&  isset($temp[0]->id))
  {
      $data[]=$temp[0];
  }
  
  // for documents
  $sql="SELECT {$db->prefix}profilemodule_documents.id master_id, {$db->prefix}profilemodule_documents.* FROM `{$db->prefix}profilemodule_documents` WHERE mp4_file = '' AND flv_file <> '' AND id NOT IN (SELECT item_id FROM {$db->prefix}videoconvert_issue where item_type = 1) LIMIT 0, 1";
  //$temp = $db->selectObject("profilemodule_documents", "mp4_file = '' AND flv_file <> ''");
  $temp = $db->selectObjectsBySql($sql);
  if (count($temp) > 0 &&  isset($temp[0]->id))
  {
      $data[]=$temp[0];
  }
  
  echo "Dump all data before convertion ...\r\n";
  print_r($data);
  
  foreach ($data as $item){
      if (!isset($item->doc_file))
        echo "Found Case ID = {$item->id} ; FLV File = {$item->file_video} ...\r\n"  ;
      else
        echo "Found Document ID = {$item->id} ; FLV File = {$item->flv_file} ...\r\n"  ;
        
       $ttime=microtime(true);
      
      // convert
      if (!isset($item->doc_file)) // is cases?
      {
          $ret = ffmpeg_toIphone_Convert($item->file_video);
          $item->mp4_file= substr ($item->file_video,0, strlen($item->file_video)-3)."mp4";
      }
      else
      {
          $ret = ffmpeg_toIphone_Convert($item->flv_file);
          $item->mp4_file= substr ($item->flv_file,0, strlen($item->flv_file)-3)."mp4";
      }
      
      $ftime=microtime(true);
      
      $time= $ftime-$ttime;
      if ($time > 1)
      {
          echo "Total time for converting: {$time}(s) for {$item->mp4_file} ...\r\n"  ;
          // update
          if (!isset($item->doc_file)) // is cases?
            $db->updateObject($item, "profilemodule_cases");
          else
            $db->updateObject($item, "profilemodule_documents");
      }
      else
      {
          // something wrong with this link, email to admin
          $type=0;
          if (isset($item->doc_file))
            $type=1;
          avc_sendmail(array("trungdt@absoft.vn", "hasankurtulus@gmail.com"), $item, $type);
          
          // insert into convert issue table
          $temp= new stdClass;
          if (!isset($item->doc_file)) // is cases?
            $temp->file_path = $item->file_video;
          else
            $temp->file_path = $item->flv_file;
          $temp->item_id = $item->id;
          $temp->item_type=$type;
          $temp->send_date = time();
          
      }
  }
  
  // test cron tab
  
?>
